<?php


namespace Modules\Admin\Http\Controllers\AdminUser;


use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\General\Security\Authorization\Manager;
use Modules\Common\Models\AdminPermission;
use Modules\Common\Util\Api;
use Illuminate\Support\Facades\DB;

class Retrieve
{
    /**
     * @Route(path=/api/admin/adminuser/with-permission)
     */
    public function index()
    {
        $adminUser = Gateway::AdminUser();
        $casbinItems = (new Manager())->getImplicitPermissionsForUser($adminUser->id);
        $permissionIds = collect($casbinItems)->pluck(1)->map(function ($item) {
            return substr($item, 1);
        })->unique()->all();
        $permissions = AdminPermission::findMany($permissionIds, ['id', 'path', 'method', 'disable']);
        $disabledPermissions = AdminPermission::where('disable', 1)->get(['id', 'path', 'method', 'disable']);
        $permissions->merge($disabledPermissions);
        $permissions->each(function ($permission) use ($casbinItems) {
            $permission->branches = collect($casbinItems)->where(1, "p{$permission->id}")->pluck(2)->map(function ($branch) {
                return substr($branch, 1);
            })->unique()->all();
            $permission->branches=array_values($permission->branches);
        });
        $adminUser->permissions = $permissions;
        return Api::success($adminUser);
    }
    
    /**
     * @Route(path=/api/admin/adminuser-info)
     */
    public function adminuserInfo()
    {
        $adminUser = auth('api')->user();
        $enterprise = DB::connection('platform')->table('enterprise')->where('id', '=', $adminUser->eid)->first();
        $enterprise_setting = DB::connection('platform')->table('enterprise_setting')->where('eid', '=', $adminUser->eid)->first();
        $adminUser->enterprise_name = $enterprise->name;
        $adminUser->integral_shop_open = $enterprise_setting->integral_shop_open;
        $adminUser->read_subscription_open = $enterprise_setting->read_subscription_open;
        $adminUser->user_operation_open = $enterprise_setting->user_operation_open;
        return Api::success($adminUser);
    }
    
    

}
